package cn.uyunsky.platform.jaxb;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class XmlConvertImpl implements XmlConvert {

	private static Log log = LogFactory.getLog(XmlConvertImpl.class);

	//是否格式化xml
	private boolean formatXml = true;

	public void setFormatXml(boolean formatXml) {
		this.formatXml = formatXml;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T unpack(Class<T> clazz, Reader reader) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
			// 目前只有一个接口，对应一个对象;如果将来多个接口并且对象不同,则需要根据业务标示来获取对应的对象
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			Object bean = unmarshaller.unmarshal(reader);
			if (log.isDebugEnabled())
				log.debug("转换xml到bean:" + bean);
			return (T) bean;
		} catch (JAXBException e) {
			if (log.isErrorEnabled())
				log.error("转换xml到bean异常", e);
			return null;
		}
	}

	@Override
	public <T> T unpack(Class<T> clazz, InputStream in) {
		try {
			InputStreamReader reader = new InputStreamReader(in, "UTF-8");
			return this.unpack(clazz, reader);
		} catch (UnsupportedEncodingException e) {
			if (log.isErrorEnabled())
				log.error("转换xml到bean异常", e);
			return null;
		}
	}

	@Override
	public void pack(Object bean, Writer writer) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(bean.getClass());
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatXml);
			marshaller.marshal(bean, writer);
		} catch (JAXBException e) {
			if (log.isErrorEnabled())
				log.error("组装xml异常", e);
		}
		return;
	}

}
